#coding=utf-8
import sys, os

def call(args, options, global_options):
    from uliweb.core.SimpleFrame import Dispatcher
    from uliweb.orm import Begin, Commit, Rollback, get_connection

    app = Dispatcher(apps_dir=global_options.apps_dir, start=False)
    Begin()
    try:
        process(args, options, global_options)
        Commit()
    except:
        Rollback()
        import traceback
        traceback.print_exc()

def process(args, options, global_options):
    print 'Processing people_info file...'
    if len(args) != 2:
        print "Error, the command line is not right"
        print "     uliweb call import_people dir"
        return
        
    import_(args[1], options, global_options)
        
def import_(dir, options, global_options):
    import csv
    from uliweb.orm import get_model
    from glob import glob
    from sqlalchemy.sql import exists
    from uliweb import settings
    from sqlalchemy.sql import func
    
    Department = get_model('department')
    Human = get_model('human')
    
    c_n = 0
    n_n = 0
    n = 0
    filenames = glob(os.path.join(dir, 'person_info_*'))
    if len(filenames) > 0:
        filename = filenames[0]
    else:
        filename = None
    if not filename:
        print "Can't find the person_info file in %s" % dir
        return
        
    Human.table.update(Human.c.type!='4').execute(delete_flag=True)

    for line in csv.reader(open(filename), delimiter='|'):
        try:
            _, name, login_name, _, typename, _, department = line
        except:
            print 'Error: line [%s]' % line
            continue
        name = unicode(name, 'utf-8')
        login_name = unicode(login_name, 'utf-8')
        department = unicode(department, 'utf-8')
        if typename == '借调':
            type = '1'
        elif typename == '公司':
            type = '2'
        elif typename == '中心':
            type = '3'
        else:
            print "Can't find the human type %s" % typename
            sys.exit(1)
        
        d = Department.get(Department.c.code==department)
        if d:
            if settings.ORM.CONNECTION.startswith('mysql'):
                condition = (Human.c.login_name==func.binary(login_name))
            else:
                condition = (Human.c.login_name==login_name)
            h = Human.get(condition)
            if h:
                if h._department_ != department or h.name != name or h.type != type:
                    if global_options.verbose:
                        print 'changed', name, login_name, department, type, '(', h.name, h._department_, h.type, ')'
                    h.update(department=department, name=name, type=type, delete_flag=False)
                    h.save()
                    c_n += 1
                else:
                    h.delete_flag = False
                    h.save()
            else:
                h = Human(name=name, login_name=login_name, department=department, type=type,
                    assigned=False, delete_flag=False)
                h.save()
                n_n += 1
                if global_options.verbose:
                    print 'added', name, login_name, department, type
        else:
            print "Can't find the department [%s]" % department
            continue
        
        n += 1
    
    Resource = get_model('resource')
    Resource.table.delete(exists().where((Resource.c.user == Human.c.login_name) & (Human.c.delete_flag==True))).execute()
    
    os.rename(filename, os.path.join(os.path.dirname(filename), 'bak_' + os.path.basename(filename)))
    print "Total process %d, and added %d, changed %d" % (n, n_n, c_n)